package com.birdboot.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**响应对象*/
public class HttpServletResponse {
    private Socket socket;
    private int statusCode = 200;
    private String statusReason = "OK";
    private File contentFile;
    public HttpServletResponse(Socket socket) {
        this.socket = socket;
    }


    public void response()throws IOException{
        sendStatusLine();
        sendHeaders();
        sendContent();
    }
    //发送状态行
    private void sendStatusLine()throws IOException{
        println("HTTP/1.1 "+statusCode+" "+statusReason);
    }
    //发送响应头
    private void sendHeaders()throws IOException{
        println("Content-Type: text/html");
        System.out.println("1111111111");
        println("Content-Length:"+contentFile.length());
        System.out.println("222222222");
        println("");
    }
    //发送响应正文
    private void sendContent()throws IOException{
        OutputStream out = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(contentFile);
        byte [] data = new byte[1024*10];
        int len;
        while ((len = fis.read(data)) != -1){
            out.write(data,0,len);
        }}


    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);
        out.write(10);
    }

    public Socket getSocket() {
        return socket;
    }
    public void setSocket(Socket socket) {
        this.socket = socket;
    }
    public int getStatusCode() {
        return statusCode;
    }
    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }
    public String getStatusReason() {
        return statusReason;
    }
    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }
    public File getContentFile() {
        return contentFile;
    }
    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
    }
}
